<?php
// 简单的MQTT连接测试脚本
use Simps\MQTT\Client;
use Simps\MQTT\Config\ClientConfig;
echo "开始MQTT连接测试...\n";

// 1. 测试TCP连接
echo "1. 测试TCP连接到 127.0.0.1:1883...\n";
$socket = @fsockopen('127.0.0.1', 1883, $errno, $errstr, 5);
if ($socket) {
    echo "   ✅ TCP连接成功\n";
    fclose($socket);
} else {
    echo "   ❌ TCP连接失败: $errstr ($errno)\n";
    exit(1);
}

// 2. 检查Redis扩展
echo "2. 检查PHP扩展...\n";
if (extension_loaded('sockets')) {
    echo "   ✅ sockets扩展已加载\n";
} else {
    echo "   ❌ sockets扩展未加载\n";
}

if (extension_loaded('swoole')) {
    echo "   ✅ swoole扩展已加载\n";
} else {
    echo "   ⚠️  swoole扩展未加载（可能影响MQTT客户端）\n";
}

// 3. 测试MQTT客户端库
echo "3. 测试MQTT客户端库...\n";
try {
    require_once __DIR__ . '/vendor/autoload.php';
    
    
    
    echo "   ✅ MQTT客户端库加载成功\n";
    
    // 4. 尝试创建客户端
    echo "4. 创建MQTT客户端...\n";
    $clientConfig = new ClientConfig();
    $clientConfig->setKeepAlive(60)
                 ->setClientId('test_client_' . uniqid());
    
    $client = new Client('127.0.0.1', 1883, $clientConfig, 2);
    echo "   ✅ MQTT客户端创建成功\n";
    
    // 5. 尝试连接
    echo "5. 尝试连接到EMQ X...\n";
    $result = $client->connect(true);

    echo "   连接返回值: " . var_export($result, true) . "\n";
    echo "   连接返回值类型: " . gettype($result) . "\n";

    if ($result === true || is_array($result)) {
        echo "   ✅ MQTT连接成功！\n";

        // 6. 测试订阅
        echo "6. 测试订阅主题...\n";
        try {
            $subResult = $client->subscribe(['test/topic' => 0]);
            echo "   订阅返回值: " . var_export($subResult, true) . "\n";

            if ($subResult === true || is_array($subResult)) {
                echo "   ✅ 订阅成功！\n";

                // 7. 测试发布
                echo "7. 测试发布消息...\n";
                $pubResult = $client->publish('test/topic', 'Hello MQTT!');
                echo "   发布返回值: " . var_export($pubResult, true) . "\n";

                if ($pubResult === true) {
                    echo "   ✅ 发布成功！\n";
                } else {
                    echo "   ❌ 发布失败\n";
                }
            } else {
                echo "   ❌ 订阅失败\n";
            }
        } catch (\Throwable $e) {
            echo "   ❌ 订阅异常: " . $e->getMessage() . "\n";
        }

        $client->close();
        echo "   ✅ 连接已关闭\n";
    } else {
        echo "   ❌ MQTT连接失败\n";
    }
    
} catch (\Throwable $e) {
    echo "   ❌ 测试异常: " . $e->getMessage() . "\n";
    echo "   文件: " . $e->getFile() . ":" . $e->getLine() . "\n";
}

echo "\n测试完成。\n";
